import axios from "axios";
import { AxiosRetry } from './axiosClass'

axios.defaults.baseURL='http://127.0.0.1:3000'

// 添加请求拦截器
axios.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    // 在请求头中添加token
    config.headers.Authorization = localStorage.getItem("accessToken");
    if (config.url == "/refreshToken") {
      config.headers.Authorization = localStorage.getItem("refreshToken");
    }
    return config;
  },
);


/**先到拦截器*/
axios.interceptors.response.use(res => {
  if (res.status != 200) {    
    return Promise.reject(res.data);
  }
  return Promise.resolve(res.data)
});

const axiosRetry = new AxiosRetry({
  onSuccess: (res) => {
    let { accessToken } = res.data
    localStorage.setItem("accessToken", accessToken);
  },
  onError: () => {
    console.log('refreshToken过期，需要重新登录');
  },
});


export const request = (url: string) => {
  return axiosRetry.requestWrapper(() => {
    return axios({
      method: "get",
      url: `${url}`,
    })
  });
}

